<template>
  <view class="publish-page">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-left" @click="cancelPublish">
        <text class="cancel-text">取消</text>
      </view>
      <view class="nav-title">编辑内容</view>
      <view class="nav-right" @click="publishContent">
        <text class="publish-text" :class="{ disabled: !canPublish }">发布</text>
      </view>
    </view>
    
    <!-- 内容区域 -->
    <scroll-view scroll-y="true" class="content-scroll">
      <!-- 话题区域 -->
      <view class="topic-section">
        <view class="topic-header" @click="openTopicsModal">
          <text class="topic-title">#添加话题</text>
          <uni-icons type="right" size="14" color="#999" />
        </view>
        
        <!-- 已选话题 -->
        <view class="selected-topics" v-if="selectedTopics.length > 0">
          <view 
            v-for="(topic, index) in selectedTopics" 
            :key="index" 
            class="topic-tag"
          >
            <text class="topic-text">{{ topic }}</text>
          </view>
        </view>
      </view>
      
      <!-- 提示信息 -->
      <view class="tips-section">
        <view class="tips-title">车主圈发言小贴士：</view>
        <view class="tips-content">
          <text class="tips-text">1.发表内容请选择恰当的话题，并保持文明用语，不当言论可能会被隐藏；</text>
          <text class="tips-text">2.遇到不和谐的言论请直接举报，发表人身攻击、营销诈骗、辱骂等敏感言论将会被禁言；</text>
          <text class="tips-text">3.遇到产品适用的问题，可以在"我的-问题反馈"提交您的宝贵意见，也可以选择话题#车主圈使用反馈#发表建议。</text>
        </view>
      </view>
      
      <!-- 文本输入区域 -->
      <view class="text-input-section">
        <textarea 
          v-model="content"
          class="content-textarea"
          placeholder="分享你的想法..."
          placeholder-style="color: #999"
          auto-height
          maxlength="500"
        ></textarea>
      </view>
      
      <!-- 图片上传区域 -->
      <view class="image-upload-section">
        <view class="image-grid">
          <!-- 已选择的图片 -->
          <view v-for="(file, index) in fileList" :key="index" class="image-item">
            <image :src="file.url || file.tempFilePath" mode="aspectFill" class="image-preview"></image>
            <view class="image-actions">
              <view class="delete-btn" @click="handleDelete(index)">
                <uni-icons type="close" size="16" color="#fff" />
              </view>
              <view v-if="file.status === 'uploading'" class="uploading-status">
                <text>{{ file.message }}</text>
              </view>
              <view v-if="file.status === 'failed'" class="fail-status">
                <text>{{ file.message }}</text>
                <view class="retry-btn" @click="retryUpload(index)">
                  <uni-icons type="reload" size="16" color="#fff" />
                </view>
              </view>
            </view>
          </view>
          
          <!-- 添加图片按钮 -->
          <view v-if="fileList.length < 9" class="add-image-btn" @click="chooseImages">
            <uni-icons type="camera-fill" size="32" color="#D3D4D6" />
            <text class="add-text">添加图片</text>
          </view>
        </view>
      </view>
      
      <!-- 位置信息 -->
      <view class="location-section" @click="selectLocation">
        <view class="location-item">
          <uni-icons type="map" size="16" color="#666" />
          <text class="location-text">{{ selectedLocation || '发送当前位置' }}</text>
          <uni-icons type="right" size="14" color="#999" />
        </view>
      </view>
    </scroll-view>
    
    <!-- 话题选择弹窗 -->
    <uni-popup ref="topicsPopup" type="bottom" :maskClick="true" :safeArea="true">
      <view class="topics-popup-content">
        <view class="popup-header">
          <text class="popup-title">选择话题</text>
          <text class="popup-close" @click="closeTopicsModal">关闭</text>
        </view>
        <scroll-view scroll-y="true" class="topics-list">
          <view 
            v-for="(topic, index) in hotTopics" 
            :key="index" 
            class="topic-option"
            :class="{ selected: selectedTopics.includes(topic) }"
            @click="toggleTopic(topic)"
          >
            <text class="topic-name">{{ topic }}</text>
            <uni-icons 
              v-if="selectedTopics.includes(topic)" 
              type="success" 
              size="16" 
              color="#07C160" 
            />
          </view>
        </scroll-view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { getHotTopics, publishMoment } from '@/api/moments/index.js';
import { getLocation } from '@/utils/location.js';

export default {
  data() {
    return {
      selectedTopics: [],
      hotTopics: [
        '#好意见会实现！~',
        '#这些升级 您试了吗？~',
        '#车主圈使用反馈#',
        '#分享出车生活#',
        '#司机风采展示#'
      ],
      fileList: [],
      formData: {
        type: 'image'
      },
      selectedLocation: '',
      imageFiles: [],
      content: ''
    };
  },
  
  computed: {
    canPublish() {
      // 至少需要选择一个话题才能发布
      return this.selectedTopics.length > 0;
    }
  },
  
  onLoad() {
    // 加载热门话题
    this.loadHotTopics();
  },
  
  methods: {
    // 加载热门话题
    loadHotTopics() {
      getHotTopics().then(res => {
        if (res.code === 0 && res.data && res.data.length > 0) {
          this.hotTopics = res.data;
        }
      }).catch(err => {
        console.error('加载热门话题失败:', err);
        // 使用模拟数据
        this.hotTopics = [
          '#好意见会实现！~',
          '#这些升级 您试了吗？~',
          '#车主圈使用反馈#',
          '#分享出车生活#',
          '#司机风采展示#'
        ];
      });
    },
    
    // 打开话题选择弹窗
    openTopicsModal() {
      this.$refs.topicsPopup.open();
    },
    
    // 关闭话题选择弹窗
    closeTopicsModal() {
      this.$refs.topicsPopup.close();
    },
    
    // 切换话题选择状态
    toggleTopic(topic) {
      const index = this.selectedTopics.indexOf(topic);
      if (index > -1) {
        this.selectedTopics.splice(index, 1);
      } else {
        this.selectedTopics.push(topic);
      }
    },
    
    // 选择位置
    selectLocation() {
      // 调用位置选择API
      getLocation().then(res => {
        if (res.code === 0) {
          this.selectedLocation = res.data.address;
        }
      }).catch(err => {
        console.error('获取位置失败:', err);
        // 模拟选择位置
        this.selectedLocation = '杭州市';
        uni.showToast({
          title: '已选择位置：杭州市',
          icon: 'none'
        });
      });
    },
    
    // 选择图片
    chooseImages() {
      const maxCount = 9 - this.fileList.length;
      
      uni.chooseImage({
        count: maxCount,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePaths = res.tempFilePaths;
          const tempFiles = res.tempFiles;
          
          // 检查文件大小
          for (let i = 0; i < tempFiles.length; i++) {
            const file = tempFiles[i];
            if (file.size > 10 * 1024 * 1024) { // 10MB
              this.handleOversize({ name: `image${i + 1}` });
              return;
            }
          }
          
          // 添加到文件列表并开始上传
          tempFilePaths.forEach((path, index) => {
            const file = {
              url: path,
              tempFilePath: path,
              status: 'uploading',
              message: '上传中...'
            };
            
            this.fileList.push(file);
            this.uploadImageFile(file, this.fileList.length - 1);
          });
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
        }
      });
    },
    
    // 上传图片文件
    uploadImageFile(file, index) {
      // 调用图片上传接口
      uni.uploadFile({
        url: '/api/upload/image', // 后端图片上传接口
        filePath: file.tempFilePath,
        name: 'file',
        formData: this.formData,
        success: (res) => {
          // 解析上传结果
          try {
            const data = JSON.parse(res.data);
            if (data.code === 0 && data.data && data.data.url) {
              // 上传成功，更新文件状态
              file.status = 'success';
              file.message = '';
              file.url = data.data.url; // 使用服务器返回的图片地址
              
              // 更新文件列表
              this.$set(this.fileList, index, file);
              
              // 更新imageFiles数组
              this.updateImageFiles();
            } else {
              // 上传失败
              file.status = 'failed';
              file.message = data.msg || '上传失败';
              this.$set(this.fileList, index, file);
              console.error('图片上传失败:', data.msg || '未知错误');
            }
          } catch (e) {
            file.status = 'failed';
            file.message = '上传失败';
            this.$set(this.fileList, index, file);
            console.error('图片上传结果解析失败:', e);
          }
        },
        fail: (err) => {
          file.status = 'failed';
          file.message = '上传失败';
          this.$set(this.fileList, index, file);
          console.error('图片上传请求失败:', err);
        }
      });
    },
    
    // 文件超出大小限制
    handleOversize(file) {
      uni.showToast({
        title: `文件${file.name}大小超出10MB限制`,
        icon: 'none'
      });
    },
    
    // 删除图片
    handleDelete(index) {
      this.fileList.splice(index, 1);
      // 更新imageFiles数组
      this.updateImageFiles();
    },
    
    // 重试上传失败的图片
    retryUpload(index) {
      const file = this.fileList[index];
      
      // 检查文件状态是否为失败
      if (file && file.status === 'failed') {
        // 重置文件状态
        file.status = 'uploading';
        file.message = '上传中...';
        this.$set(this.fileList, index, file);
        
        // 重新上传
        this.uploadImageFile(file, index);
      }
    },
    
    // 更新imageFiles数组，只保留成功上传的图片地址
    updateImageFiles() {
      this.imageFiles = this.fileList
        .filter(file => file.status === 'success' && file.url)
        .map(file => file.url);
    },
    
    // 取消发布
    cancelPublish() {
      uni.showModal({
        title: '提示',
        content: '确定要放弃编辑吗？',
        success: res => {
          if (res.confirm) {
            uni.navigateBack();
          }
        }
      });
    },
    
    // 发布内容
    publishContent() {
      if (!this.canPublish) {
        uni.showToast({
          title: '请至少选择一个话题',
          icon: 'none'
        });
        return;
      }
      
      const publishData = {
        content: this.content,
        topics: this.selectedTopics.join(' '),
        images: this.imageFiles,
        location: this.selectedLocation
      };
      
      uni.showLoading({
        title: '发布中...'
      });
      
      // 使用实际API
      publishMoment(publishData).then(res => {
        if (res.code === 0) {
          uni.showToast({
            title: '发布成功',
            icon: 'success',
            complete: () => {
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            }
          });
        } else {
          uni.showToast({
            title: res.msg || '发布失败，请重试',
            icon: 'none'
          });
        }
      }).catch(err => {
        console.error('发布失败:', err);
        uni.showToast({
          title: '网络异常，请重试',
          icon: 'none'
        });
      }).finally(() => {
        uni.hideLoading();
      });
    }
  }
};
</script>

<style scoped>
.publish-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.nav-bar {
  height: 88rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #eee;
  position: sticky;
  top: 0;
  z-index: 100;
}

.cancel-text {
  font-size: 32rpx;
  color: #666;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}

.publish-text {
  font-size: 32rpx;
  color: #3C6CFC;
  font-weight: 500;
}

.publish-text.disabled {
  color: #ccc;
}

/* 内容滚动区域 */
.content-scroll {
  flex: 1;
  padding: 30rpx;
}

/* 话题区域 */
.topic-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 24rpx 30rpx;
  margin-bottom: 24rpx;
}

.topic-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.topic-title {
  font-size: 32rpx;
  color: #666;
}

.selected-topics {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-top: 20rpx;
}

.topic-tag {
  padding: 8rpx 20rpx;
  background-color: #F4F5F6;
  border-radius: 20rpx;
  font-size: 28rpx;
  color: #333;
}

/* 提示信息 */
.tips-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 24rpx 30rpx;
  margin-bottom: 24rpx;
}

/* 文本输入区域 */
.text-input-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 24rpx;
}

.content-textarea {
  width: 100%;
  min-height: 200rpx;
  font-size: 32rpx;
  color: #333;
  line-height: 1.6;
}

.tips-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 16rpx;
}

.tips-content {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.tips-text {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
}

/* 图片上传区域 */
.image-upload-section {
      margin-top: 20rpx;
      padding: 0 30rpx;
    }
    
    .image-grid {
      display: flex;
      flex-wrap: wrap;
    }
    
    .image-item {
      position: relative;
      width: 200rpx;
      height: 200rpx;
      margin-right: 20rpx;
      margin-bottom: 20rpx;
      border-radius: 10rpx;
      overflow: hidden;
      background-color: #f7f7f7;
    }
    
    .image-item:nth-child(4n) {
      margin-right: 0;
    }
    
    .image-preview {
      width: 100%;
      height: 100%;
    }
    
    .image-actions {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0, 0, 0, 0.5);
      padding: 5rpx 10rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .delete-btn {
      width: 40rpx;
      height: 40rpx;
      border-radius: 50%;
      background-color: rgba(0, 0, 0, 0.7);
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .uploading-status text,
    .fail-status text {
      color: #fff;
      font-size: 24rpx;
    }
    
    .retry-btn {
      margin-left: 10rpx;
      width: 40rpx;
      height: 40rpx;
      border-radius: 50%;
      background-color: rgba(0, 0, 0, 0.7);
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .add-image-btn {
      width: 200rpx;
      height: 200rpx;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      border: 1px dashed #D3D4D6;
      border-radius: 10rpx;
      background-color: #f7f7f7;
    }
    
    .add-text {
      margin-top: 10rpx;
      font-size: 24rpx;
      color: #D3D4D6;
    }

/* 位置信息 */
.location-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
}

.location-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.location-text {
  flex: 1;
  margin: 0 12rpx;
  font-size: 30rpx;
  color: #333;
}

/* 话题弹窗 */
.topics-popup-content {
  background-color: #fff;
  padding: 0 0 30rpx 0;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.popup-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}

.popup-close {
  font-size: 32rpx;
  color: #666;
}

.topics-list {
  max-height: 60vh;
  padding: 0 30rpx;
}

.topic-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 28rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.topic-option.selected {
  color: #07C160;
}

.topic-name {
  font-size: 32rpx;
  color: #333;
}

.topic-option.selected .topic-name {
  color: #07C160;
}
</style>